const express = require('express');
const router = express.Router();
const pool = require('../db/db');
const {executeQuery} = require("../db/execute");

// 添加商品
router.post('/add', (req, res) => {
    const { goodsName, price, storeNbr, imgUrl } = req.body;
    const query = 'INSERT INTO goods (goods_name, price, store_nbr, img_url) VALUES (?, ?, ?, ?)';
    const params = [goodsName, price, storeNbr, imgUrl];
    executeQuery(query, params, '商品添加成功', res);
});

// 删除商品
router.post('/delete', (req, res) => {
    const { id } = req.body;
    const query = 'DELETE FROM goods WHERE goods_id = ?';
    const params = [id];
    executeQuery(query, params, '商品删除成功', res);
});

// 更新商品
router.post('/update', (req, res) => {
    const { id, goodsName, price, storeNbr, imgUrl } = req.body;
    const query = 'UPDATE goods SET goods_name = ?, price = ?, store_nbr = ?, img_url = ? WHERE goods_id = ?';
    const params = [goodsName, price, storeNbr, imgUrl, id];
    executeQuery(query, params, '商品更新成功', res);
});

// 查询商品（全量）
router.post('/list', (req, res) => {
    const { goodsName } = req.body;
    const query = 'SELECT goods_id AS goodsId, goods_name AS goodsName, price, store_nbr AS storeNbr, img_url AS imgUrl FROM goods WHERE goods_name LIKE ?';
    const params = [`%${goodsName || ''}%`];
    executeQuery(query, params, '商品查询成功', res);
});

// 查询商品（分页）
router.post('/listPage', (req, res) => {
    const { pageNum, pageSize, goodsName } = req.body;
    const offset = (pageNum - 1) * pageSize;
    const query = 'SELECT goods_id AS goodsId, goods_name AS goodsName, price, store_nbr AS storeNbr, img_url AS imgUrl FROM goods WHERE goods_name LIKE ? LIMIT ?, ?';
    const params = [`%${goodsName || ''}%`, offset, pageSize];
    executeQuery(query, params, '商品查询成功', res);
});


module.exports = router;
